package com.cxq.boot.provider;

import com.alibaba.fastjson.JSON;
import com.cxq.boot.dto.AccessTokenDTO;
import com.cxq.boot.strategy.dto.GithubUser;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * provider：提供者，提供第三方支持的能力
 */
//使用 OkHttp https://square.github.io/okhttp/ 获取 Github 用户
@Component
public class GitHubProvider {

    @Value("${github.client.id}")
    private String clientId;
    @Value("${github.client.secret}")
    private String clientSecret;
    @Value("${github.redirect.uri}")
    private String redirectUri;

    /**
     * 将数据发布到服务，如 Github
     * @param accessTokenDTO 请求参数
     * @return access_token 值
     */
    public String getAccessToken(AccessTokenDTO accessTokenDTO) {

        accessTokenDTO.setClient_id(clientId);
        //第二个：0f1b1655de7f8c6ba2736fdf6fca0f7159a367f6
        accessTokenDTO.setClient_secret(clientSecret);
        accessTokenDTO.setRedirect_uri(redirectUri);

        MediaType mediaType = MediaType.get("application/json; charset=utf-8");
        OkHttpClient client = new OkHttpClient();

        RequestBody body = RequestBody.create(mediaType,JSON.toJSONString(accessTokenDTO));
        Request request = new Request.Builder()
                .url("https://github.com/login/oauth/access_token")
                .post(body)
                .build();
        try (Response response = client.newCall(request).execute()) {
            String string = response.body().string();
            String token = string.split("&")[0].split("=")[1];
            System.out.println("github token:" + token);
            return token;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 下载一个 URL 并将其内容打印为字符串
     * @param accessToken
     * @return Github 用户
     */
    public GithubUser getUser(String accessToken){
        OkHttpClient client = new OkHttpClient();
        //修改前
        /*Request request = new Request.Builder()
                .url("https://api.github.com/user?access_token=" + accessToken)
                .build();*/
        //使用 header 访问
        Request request = new Request.Builder()
                .url("https://api.github.com/user?access_token=" + accessToken)
                .header("Authorization","token " + accessToken)
                .build();
        try {
            Response response = client.newCall(request).execute();
            String s = response.body().string();
            //fastjson可以自动把下划线标识映射到驼峰的属性，如GithubUser的avatarUrl
            GithubUser githubUser = JSON.parseObject(s, GithubUser.class);
            return githubUser;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}